import bluetooth
from ble_advertising import advertising_payload

# 定义事件和标志
_IRQ_CENTRAL_CONNECT = 1
_IRQ_CENTRAL_DISCONNECT = 2
_IRQ_GATTS_WRITE = 3

_FLAG_WRITE = 0x0008
_FLAG_NOTIFY = 0x0010

# 自定义服务和特征的 UUID
_SERVICE_UUID = bluetooth.UUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b")
_CHAR_UUID = bluetooth.UUID("beb5483e-36e1-4688-b7f5-ea07361b26a8")

# 定义服务和特征
_CHAR = (
    _CHAR_UUID,
    _FLAG_WRITE | _FLAG_NOTIFY,
)
_SERVICE = (
    _SERVICE_UUID,
    (_CHAR,),
)
_SERVICES = (_SERVICE,)

class BLEHandler:
    def __init__(self, ble, name="mpy-ble"):
        self._ble = ble
        self._ble.active(True)
        self._ble.irq(self._irq)
        ((self._handle,),) = self._ble.gatts_register_services(_SERVICES)
        self._connections = set()
        self._payload = advertising_payload(name=name, services=[_SERVICE_UUID])
        self._advertise()

    def _irq(self, event, data):
        if event == _IRQ_CENTRAL_CONNECT:
            conn_handle, _, _ = data
            self._connections.add(conn_handle)
        elif event == _IRQ_CENTRAL_DISCONNECT:
            conn_handle, _, _ = data
            self._connections.remove(conn_handle)
            self._advertise()
        elif event == _IRQ_GATTS_WRITE:
            conn_handle, value_handle = data
            if value_handle == self._handle:
                data = self._ble.gatts_read(self._handle)
                print("Received data:", data)

    def _advertise(self, interval_us=500000):
        self._ble.gap_advertise(interval_us, adv_data=self._payload)

    def send_large_data(self, large_data):
        chunk_size = 20  # BLE 数据包最大长度通常为 20 字节
        for i in range(0, len(large_data), chunk_size):
            chunk = large_data[i:i + chunk_size]
            for conn_handle in self._connections:
                self._ble.gatts_notify(conn_handle, self._handle, chunk)

# 初始化 BLE
ble = bluetooth.BLE()
ble_handler = BLEHandler(ble)